package com.environment_pro.monitor.util;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.apache.log4j.Logger;

import com.environment_pro.monitor.model.TbSystemConf;
import com.environment_pro.monitor.service.TbSystemConfService;

import java.sql.*;
import java.util.List;
import java.util.Properties;

/**
 * Mybatis - 通用分页拦截器
 * @author 
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class}),
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class PageHelper implements Interceptor {
    private static final Logger logger = Logger.getLogger(PageHelper.class);

    @SuppressWarnings("unchecked")
	public static final ThreadLocal<Page> localPage = new ThreadLocal<Page>();

    /**
     * 开始分页
     * @param curPage
     * @param pageSize
     */
    public static void startPage(PageInfo pageInfo) {
        localPage.set(new Page<Object>(pageInfo));
    }

    /**
     * 结束分页并返回结果，该方法必须被调用，否则localPage会一直保存下去，直到下一次startPage
     * @return
     */
    @SuppressWarnings("unchecked")
	public static Page endPage() {
        Page page = localPage.get();
        localPage.remove();
        return page;
    }

    public Object intercept(Invocation invocation) throws Throwable {
        if (localPage.get() == null) {
            return invocation.proceed();
        }
        if (invocation.getTarget() instanceof StatementHandler) {
            StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
            MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
            // 分离代理对象链(由于目标类可能被多个拦截器拦截，从而形成多次代理，通过下面的两次循环
            // 可以分离出最原始的的目标类)
            while (metaStatementHandler.hasGetter("h")) {
                Object object = metaStatementHandler.getValue("h");
                metaStatementHandler = SystemMetaObject.forObject(object);
            }
            // 分离最后一个代理对象的目标类
            while (metaStatementHandler.hasGetter("target")) {
                Object object = metaStatementHandler.getValue("target");
                metaStatementHandler = SystemMetaObject.forObject(object);
            }
            MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
            //分页信息if (localPage.get() != null) {
            Page page = localPage.get();
            BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
            // 分页参数作为参数对象parameterObject的一个属性
            String sql = boundSql.getSql();
            // 重写sql
            String pageSql = buildPageSql(sql, page);
            //重写分页sql
            metaStatementHandler.setValue("delegate.boundSql.sql", pageSql);
            Connection connection = (Connection) invocation.getArgs()[0];
            // 重设分页参数里的总页数等
            setPageParameter(sql, connection, mappedStatement, boundSql, page);
            // 将执行权交给下一个拦截器
            return invocation.proceed();
        } else if (invocation.getTarget() instanceof ResultSetHandler) {
            Object result = invocation.proceed();
            Page page = localPage.get();
            page.setResult((List) result);
            return result;
        }
        return null;
    }


	/**
     * 只拦截这两种类型的
     * <br>StatementHandler
     * <br>ResultSetHandler
     * @param target
     * @return
     */
    public Object plugin(Object target) {
        if (target instanceof StatementHandler || target instanceof ResultSetHandler) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    public void setProperties(Properties properties) {

    }

    /**
     * 修改原SQL为分页SQL
     * @param sql
     * @param page
     * @return
     */
    private String buildPageSql(String sql, Page page) {
    	StringBuilder pageSql = new StringBuilder(2000);
        String beginrow = String.valueOf((page.getCurPage() - 1) * page.getPageSize());
        pageSql.append(sql);
        pageSql.append(" limit " + beginrow + "," + page.getPageSize());
        logger.debug(pageSql.toString());
        return pageSql.toString();
    }
    
    /**
     * 如果记录总数获取时间操作配置时间重新获取记录总数
     * @param sql
     * @param connection
     * @param mappedStatement
     * @param boundSql
     * @param page
     */
    private void setPageParameter(String sql, Connection connection,
			MappedStatement mappedStatement, BoundSql boundSql, Page page) {
    	
    	int totalCount = (int) page.getTotalCount();
    	
    	//如果记录总数获取时间操作配置时间重新获取记录总数
		if((System.currentTimeMillis()-page.getTotalCountTimeMillis()) > page.getTotalCountTimeout()){
			queryPageTotalCount(sql, connection, mappedStatement, boundSql, page);
			totalCount = (int) page.getTotalCount();
		}
		//计算总页数
        int totalPage = totalCount / page.getPageSize() + ((totalCount % page.getPageSize() == 0) ? 0 : 1);
        page.setTotalPage(totalPage);
	}

    /**
     * 获取总记录数
     * @param sql
     * @param connection
     * @param mappedStatement
     * @param boundSql
     * @param page
     */
    @SuppressWarnings("unchecked")
	private void queryPageTotalCount(String sql, Connection connection, MappedStatement mappedStatement,
                                  BoundSql boundSql, Page page) {
        // 记录总记录数
        String countSql = "select count(0) from (" + sql + ") as temp";
        //logger.debug(countSql.toString());
        PreparedStatement countStmt = null;
        ResultSet rs = null;
        try {
        	int totalCount = (int) page.getTotalCount();
	        countStmt = connection.prepareStatement(countSql);
	        BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,
	                    boundSql.getParameterMappings(), boundSql.getParameterObject());
	        setParameters(countStmt, mappedStatement, countBS, boundSql.getParameterObject());
	        rs = countStmt.executeQuery();
	        if (rs.next()) {
	            totalCount = rs.getInt(1);
	        }
	        page.setTotalCount(totalCount);
	        page.setTotalCountTimeMillis(System.currentTimeMillis());
        } catch (SQLException e) {
            logger.error("Ignore this exception", e);
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.error("Ignore this exception", e);
            }
            try {
                countStmt.close();
            } catch (SQLException e) {
                logger.error("Ignore this exception", e);
            }
        }
    }

    /**
     * 代入参数值
     * @param ps
     * @param mappedStatement
     * @param boundSql
     * @param parameterObject
     * @throws SQLException
     */
    private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,
                               Object parameterObject) throws SQLException {
        ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
        parameterHandler.setParameters(ps);
    }

    /**
     * Description: 分页
     * Author: 
     * Update: (2014-04-16 10:56)
     */
    public static class Page<E> {
        private int curPage;
        private int pageSize;
        private int startRow;
        private int endRow;
        private long totalCount;
        private Long totalCountTimeMillis;
        private Integer totalCountTimeout;
		private int totalPage;
        private List<E> result;

        public Page(PageInfo pageInfo) {
            this.curPage = pageInfo.getCurPage();
            this.pageSize = pageInfo.getPageSize() ;
            this.totalCount = pageInfo.getTotalCount() ;
            this.totalCountTimeMillis = pageInfo.getTotalCountTimeMillis() ;
            this.totalCountTimeout = pageInfo.getTotalCountTimeout();
            this.startRow = curPage > 0 ? (curPage - 1) * pageSize : 0;
            this.endRow = curPage * pageSize;
        }

        public List<E> getResult() {
            return result;
        }

        public void setResult(List<E> result) {
            this.result = result;
        }

        public int getTotalPage() {
            return totalPage;
        }

        public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
        }

        public int getEndRow() {
            return endRow;
        }

        public void setEndRow(int endRow) {
            this.endRow = endRow;
        }

        public int getCurPage() {
            return curPage;
        }

        public void setCurPage(int curPage) {
            this.curPage = curPage;
        }

        public int getPageSize() {
            return pageSize;
        }

        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }

        public int getStartRow() {
            return startRow;
        }

        public void setStartRow(int startRow) {
            this.startRow = startRow;
        }

        public long getTotalCount() {
            return totalCount;
        }

        public void setTotalCount(long totalCount) {
            this.totalCount = totalCount;
        }
        
        public Long getTotalCountTimeMillis() {
    		return totalCountTimeMillis;
    	}

    	public void setTotalCountTimeMillis(Long totalCountTimeMillis) {
    		this.totalCountTimeMillis = totalCountTimeMillis;
    	}
    	
        public Integer getTotalCountTimeout() {
			return totalCountTimeout;
		}

		public void setTotalCountTimeout(Integer totalCountTimeout) {
			this.totalCountTimeout = totalCountTimeout;
		}


        @Override
        public String toString() {
            return "Page{" +
                    "curPage=" + curPage +
                    ", pageSize=" + pageSize +
                    ", startRow=" + startRow +
                    ", endRow=" + endRow +
                    ", totalCount=" + totalCount +
                    ", totalCountTimeMillis=" + totalCountTimeMillis +
                    ", totalPage=" + totalPage +
                    '}';
        }
    }
}
